package hw.ats.news.ds;

import hw.ats.news.model.Cate;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.util.Log;

import com.humanwares.util.StringUtil;
import com.tattermedia.allthataudio.misc.DebugFlag;

public class MultiDepthCateParser {
	private final static String TAG = "MultiDepthCateParser";
    private URL feedUrl;

    public MultiDepthCateParser(String feedUrl){
        try {
            this.feedUrl = new URL(feedUrl);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    protected InputStream getInputStream() {
        try {
            return feedUrl.openConnection().getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private Cate getCategory(NodeList items, int pid) {
    	Cate cate = new Cate();
    	cate.pid = pid;
    	
    	for (int j = 0; j < items.getLength(); j++) {
			Node property = items.item(j);
			String name = property.getNodeName();
			if (DebugFlag.isLogEnabled()) 
				Log.d(TAG, "item=" + name + "/" + property.getNodeValue());
			if (name.equalsIgnoreCase("id")) {
				cate.uid = StringUtil.intValue(property.getFirstChild()
						.getNodeValue());
			} else if (name.equalsIgnoreCase("name")) {
				StringBuilder text = new StringBuilder();
				NodeList chars = property.getChildNodes();
				for (int k = 0; k < chars.getLength(); k++) {
					text.append(chars.item(k).getNodeValue());
				}
				cate.title = text.toString();
			} else if (name.equalsIgnoreCase("icon_url")) {
				cate.icon = property.getFirstChild() == null ? null
						: property.getFirstChild().getNodeValue();
			}
    	}
    	
    	return cate;
    }
    
    
    public List<Cate> parse() {
    	if (DebugFlag.isLogEnabled()) 
    		Log.d(TAG, "S--------------------------------------------------------");
    	List<Cate> cates = new ArrayList<Cate>();
    	
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document dom = builder.parse(this.getInputStream());
			Element root = dom.getDocumentElement(); // <response>
			if (DebugFlag.isLogEnabled()) 
				Log.d(TAG, "nodeName=" + root.getNodeName());
			NodeList items = root.getChildNodes();

			for (int i = 0; i < items.getLength(); i++) {
				Node item = items.item(i);
				if (!"category".equalsIgnoreCase(item.getNodeName())) {
					continue;
				}
				
				if (DebugFlag.isLogEnabled()) 
					Log.d(TAG, "category-node=" + item.getNodeName() + "/"
						+ item.getNodeValue());

				Cate cate = new Cate();
				cate.pid = 0;
				cates.add(cate);
				
				NodeList properties = item.getChildNodes();
				Log.d(TAG, "item-length=" + properties.getLength());
				for (int j = 0; j < properties.getLength(); j++) {
					Node property = properties.item(j);
					String name = property.getNodeName();
					if (DebugFlag.isLogEnabled()) 
						Log.d(TAG, "item=" + name + "/" + property.getNodeValue());
					if (name.equalsIgnoreCase("id")) {
						cate.uid = StringUtil.intValue(property.getFirstChild()
								.getNodeValue());
					} else if (name.equalsIgnoreCase("name")) {
						StringBuilder text = new StringBuilder();
						NodeList chars = property.getChildNodes();
						for (int k = 0; k < chars.getLength(); k++) {
							text.append(chars.item(k).getNodeValue());
						}
						cate.title = text.toString();
					} else if (name.equalsIgnoreCase("icon_url")) {
						cate.icon = property.getFirstChild() == null ? null
								: property.getFirstChild().getNodeValue();
					} else if (name.equalsIgnoreCase("category")) {
						cates.add(getCategory(property.getChildNodes(), cate.uid));
					}
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
        
		if (DebugFlag.isLogEnabled()) {
			Log.d(TAG, "categories="+cates);
			Log.d(TAG, "E--------------------------------------------------------");
		}
		
		return cates;
    }
}
